[C - Socket] UDP CLIENT
Publicado por Enzo de Brito Ferber 10/03/2006
[ Hits: 12.222 ]
Homepage: http://www.maximasonorizacao.com.br
Este script testei na minha
propria máquina em terminas
diferentes, mas creio eu que
funcionará em uma rede local.
Como fazer funcionar:
Compile o script:
cc -o client client.c
Abra um terminal (xterm)
Execute o servidor.
Abra outro terminal (xterm)
Execute o cliente
P.S.: O servidor está em
outro link
#include <stdio.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#define PORT 3456
int main(int argc, char *argv[]){
int fd1, fd2;
int num_b;
int len_msg;
char msg[100];
struct sockaddr_in client;
struct sockaddr_in server;
struct hostent *host;
if(argc != 2){
printf("Error!!! %s <host>\n", argv[0]);
exit(1);
}
host = gethostbyname(argv[1]);
if(host == NULL){
printf("Impossivel resolver endereco do servidor...\n");
exit(1);
}
fd1 = socket(AF_INET, SOCK_DGRAM, 0);
if(fd1 == -1){
perror("socket");
exit(1);
}
client.sin_family = AF_INET;
client.sin_port = htons(PORT);
client.sin_addr.s_addr = INADDR_ANY;
server.sin_family = host->h_addrtype;
server.sin_port = htons(PORT);
memcpy((char *) &server.sin_addr.s_addr, host->h_addr_list[0], host->h_length);
bzero(&(client.sin_zero), 8);
bzero(&(server.sin_zero), 8);
fd2 = connect(fd1, (struct sockaddr *)&server, sizeof(struct sockaddr));
if(fd2 == -1){
perror("connect");
exit(1);
}
memset(msg, 0x0, 100);
while(1){
printf("Digite uma mensagem (exit para sair): ");
fflush(stdin);
scanf("%[^\n]", msg);
len_msg = sizeof(msg);
sendto(fd1, msg, len_msg, 0, (struct sockaddr *)&server, sizeof(struct sockaddr));
if( (strcmp("exit", msg)) == 0){
printf("\nObrigado por usar este cliente...\n");
break;
}
getchar();
}
close(fd1);
close(fd2);
}
Exemplo de Cliente e Servidor Usando Socket no Linux!
Cirurgia para acelerar o openSUSE em HD externo via USB
Void Server como Domain Control
Modo Simples de Baixar e Usar o bash-completion
Monitorando o Preço do Bitcoin ou sua Cripto Favorita em Tempo Real com um Widget Flutuante
Opções secretas em tema do Cinnamon
Como mapear unidade de rede no Linux
Como quebrar senha usando john the ripper
Alguém já testou o novo COSMIC Desktop? O que achou? (4)
Não consigo instalar distro antiga no virtualbox nem direto no hd (29)
queria saber como posso alterar a frequencia do meu ryzen 2300u pro (3)









